package com.sjh;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author jack
 * @data 2020/9/2 2:37 下午
 */
public class CallableAndFuture {
    public static void main(String[] args) {
        Future<String> future = ThreadLocalTest2.THREAD_POOL_EXECUTOR.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "callback 执行返回";
            }
        });
        System.out.println("等待返回结果");
        try {
            System.out.println("得到返回结果:" + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(ThreadLocalTest2.THREAD_POOL_EXECUTOR);
        for (int i = 1; i <= 10; i++) {
            final Integer seq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(completionService.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
